package com.hhf.springboot.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hhf.feiapicommon.model.entity.InterfaceInfo;
import com.hhf.feiapicommon.model.entity.UserInterfaceInfo;
import com.hhf.springboot.common.BaseResponse;
import com.hhf.springboot.common.ErrorCode;
import com.hhf.springboot.common.Result;
import com.hhf.springboot.exception.BusinessException;
import com.hhf.springboot.mapper.InterfaceInfoMapper;
import com.hhf.springboot.mapper.UserInterfaceInfoMapper;
import com.hhf.springboot.model.vo.InterfaceInfoVO;
import com.hhf.springboot.service.InterfaceInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author hhf
 * @Date 2024/10/12
 * @Description
 */
@RestController
@RequestMapping("/analysis")
@Slf4j
public class AnalysisController {

    @Resource
    private UserInterfaceInfoMapper userInterfaceInfoMapper;

    @Resource
    private InterfaceInfoService interfaceInfoService;

    @GetMapping("/interface/invoke/top")
    public BaseResponse<List<InterfaceInfoVO>> listInterfaceInfoInvokeAnalysis(int limit) {
        //1.统计接口调用次数(interface_info_id,total_count)
        List<UserInterfaceInfo> interfaceInfoList = userInterfaceInfoMapper.listInterfaceInfoInvokeAnalysis(limit);
        //2.根据interface_info_id分组
        Map<Long, List<UserInterfaceInfo>> collect = interfaceInfoList.stream().collect(Collectors.groupingBy(UserInterfaceInfo::getInterfaceInfoId));
        //3.根据interface_info_id查询interfaceInfo
        Set<Long> interfaceInfoIdSet = collect.keySet();
        QueryWrapper<InterfaceInfo> wrapper = new QueryWrapper<>();
        wrapper.in("id",interfaceInfoIdSet);
        List<InterfaceInfo> list = interfaceInfoService.list(wrapper);
        //判断查询结果是否为空
        if (CollectionUtil.isEmpty(list)){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }
        //4.将total_count 和 interfaceInfo 映射在一起
        List<InterfaceInfoVO> result = list.stream().map(interfaceInfo -> {
            InterfaceInfoVO interfaceInfoVO = new InterfaceInfoVO();
            BeanUtil.copyProperties(interfaceInfo, interfaceInfoVO);
            Integer totalCount = collect.get(interfaceInfo.getId()).get(0).getTotalCount();
            interfaceInfoVO.setTotalCount(totalCount);
            return interfaceInfoVO;
        }).collect(Collectors.toList());
        //5.返回
        return Result.success(result);
    }

}
